-- SkyExploreTriggerM
-- Create by chendh
-- 天空之城探索触发系统

module("SkyExploreTriggerM", package.seeall);

-- 所有的触发事件配置信息
local eventConfig = {};
-- 所有的事件选项配置信息
local optionsConfig = {};
-- 所有的问题配置信息
local questionConfig = {};

-- 模块初始化
function init()
    -- 转换下audio信息表
    local event_CSV = get_sky_explore_trigger_event_CSV();
    for i = 1, #event_CSV do
        eventConfig[event_CSV[i].id] = event_CSV[i];
    end
    local options_CSV = get_sky_explore_trigger_options_CSV();
    for i = 1, #options_CSV do
        optionsConfig[options_CSV[i].id] = options_CSV[i];
    end
    local question_CSV = get_sky_explore_trigger_question_CSV();
    for i = 1, #question_CSV do
        questionConfig[question_CSV[i].id] = question_CSV[i];
    end

    event_CSV = {};
    options_CSV = {};
    question_CSV = {};
end

-- 检索触发事件信息
function query(id, path)
    local m = eventConfig[id]

    if not m or path == "" or not path then
        return m
    end

    return m[path]
end

-- 检索事件选项信息
function queryOption(id, path)
    local m = optionsConfig[id]

    if not m or path == "" or not path then
        return m
    end

    return m[path]
end

-- 检索问题信息
function queryQuestion(id, path)
    local m = questionConfig[id]

    if not m or path == "" or not path then
        return m
    end

    return m[path]
end

-- 通知选择结果
function notifyChoiceResult(index, optionId, result)
    local skyExplore = ME.user.dbase:query("sky_explore", {});

    -- 选择成功，干掉事件
    local pos = skyExplore[index]["pos"];
    skyExplore[index] = nil;

    -- 奖励
    local bonus = result["bonus"] or {};
    for _, arr in pairs(bonus) do
        if arr[3] < 0 then
            if arr[1] == 1 then
                -- 道具
                ItemM.costAmount(ME.user, arr[2], arr[3]);
            elseif arr[1] == 2 then
                -- 对于奖励中要消耗的属性，最多降低到0
                local value = math.min(ME.user.dbase:query(arr[2], 0), -arr[3]);
                ME.user:costAttrib(arr[2], value);
            end
        else
            -- 奖励
            BonusM.doBonus(arr, "sky_explore_trigger");
        end

    end

    EventMgr.fire(event.EXPLORE_CHOICE_OPTION_RESULT, { ["result"] = result, ["pos"] = pos, ["option_id"] = optionId, ["bonus"] = bonus });
end

-- 选择选项
function choiceOption(index, option_id, extra_data)
    local skyExplore = ME.user.dbase:query("sky_explore", {});
    local exploreInfo = skyExplore[index] or {};
    local cost = exploreInfo["cost"] or {};

    -- 客户端先扣除
    if type(cost) == "table" and type(cost[option_id]) == "table" then
        for _, arr in ipairs(cost[option_id]) do
            if arr[1] == 1 then
                -- 道具
                ItemM.costAmount(ME.user, arr[2], arr[3]);
            elseif arr[1] == 2 then
                -- 属性
                ME.user:costAttrib(arr[2], arr[3]);
            end
        end
    end

    Operation.cmd_explore_trigger_choice_option(index, option_id, extra_data);
end
